#!/usr/bin/perl
#act_vgconfig.cgi
require './lvm-lib.pl';
&ReadParse();
my ($lvname, $err_msg, $newsize, $mark, @lvinfo, $l, $lv, $newblock, $minsize, $usedblocks, $fsblocks);
$config{'resizefs_lock'} = "/var/nas/lock/resizefsd";

$lvname = $in{'lvname'};
$newsize = $in{'newsize'};
$maxsize = $in{'maxsize'};
$vgfree = $in{'vgfree'};
$lvsize = $in{'lvsize'};
$lvpath = $in{'lvpath'};

my $found = 0;
@lvinfo = get_lv_info();
foreach $l (@lvinfo) {
	if($l->{'lv'} eq $lvname) {
		$found = 1;
		$lv = $l;
		last
	}
}
if(!$found){
	$err_msg = "No such LV";
	goto ERROR_OUT;
}

if($newsize =~ /[^0-9]/){
        $err_msg = $text{'invalid_size_format'};
        goto ERROR_OUT;
}

if($newsize == $lvsize){
	$err_msg = $text{'err_lvnochange'};
	goto ERROR_OUT;
}

if($newsize > $maxsize) {
	$err_msg = $text{'err_lvexceed'};
	goto ERROR_OUT;
}

if($newsize < 100){
	$err_msg = $text{'err_lvtoosmall'};
	goto ERROR_OUT;
}	
if($newsize % 4 ne 0){
	$newsize = (int($newsize / 4) + 1) * 4;
}
#If has filesystem. Get the used fs size and check if larger than new size of lv. If new size is smaller than used fs size. ERROR.
if($lv->{'status_m'} && ($newsize < $lvsize)){
	$rc0 = `e2fsck -n $lvname > /root/fs`;
	open(FH, "/root/fs");
	my @fs = <FH>;
	close(FH);
	`rm -f /root/fs`;
	my $line;
	foreach $line (@fs) {
		if($line =~ /files,\s+(\d+)\/(\d+)\s+blocks/){
			$usedblocks = $1;
			$fsblocks = $2;
			last;
		}
	}
	$minsize = int(($usedblocks * 4 / 1024) * 1.1);
	if($newsize < $minsize){
		$err_msg = $text{'err_lvfslimit'};
		goto ERROR_OUT;
	}
	$newblock = $newsize * 1024 / 4 ;
}
$err_msg  = "aaa:".$newblock."|".$newsize."|".$usedblocks."|".$minsize;
#goto ERROR_OUT;

my ($rc1, $rc2, $rc3, $rc4, $rc5, $rc6, $rc7, $rc8);
# No filesystem on LV. Directly resize LV.
if(!$lv->{'status_m'}) {
	$rc1 =  resize_lv($lvname, $lvsize, $newsize);
	if($rc1){
		$err_msg = $text{'err_resizelv'}; #"Resize lv failed";
		goto ERROR_OUT;
	}
	else{
		&redirect("index.cgi");		
	}
}
# Exist filesystem on LV. Use child process.
else{	
	my $child_pid=fork;
	if (!defined($child_pid)) {
        	#$log_ev = $text{'log_ev_mkfs_fork_err'};
        	#$log_msg= &text('log_msg_mkfs_fork_err', $volname);
        	#nas_syslog($text{'my_log_minor'}, 'naslog_warning', $log_ev, $log_msg);

        	$err_msg = "ppp".$text{'err_systemerror'};
        	goto ERROR_OUT;
	}

	if ($child_pid) {

        	open(RSFS_LOCK, ">".$config{'resizefs_lock'});
        	print RSFS_LOCK $child_pid, "\n";
        	close(RSFS_LOCK);
        	&redirect("rslvstat.cgi");
	}
	else {
        	#child process
        	while(1) {
                	if (-s $config{'resizefs_lock'}) {
                        	last;
                	}
                	sleep(1);
        	}
        	exec './rsfsd.pl', $lvname, $lvsize, $newsize, $lvpath, $newblock;
	}

}

ERROR_OUT:
&error_setup($text{'crt_err_title'});
&error($err_msg);
